package com.ruoyi.crm.moulds.email;

import com.ruoyi.crm.domain.Contract;
;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

@Service
public class CrmMailService {
    private static final  String TEMPLATE_CONTRACT_CREATED="contractCreated.html";
    @Resource
    private JavaMailSender javaMailSender;
    //模板引擎
    @Resource
    private TemplateEngine templateEngine;


    //直接注入配置类中的username；
    @Value("${spring.mail.username}")
    private String username;

    @SneakyThrows
    public void sendContractCreatedMail(Contract contract) {
        Context context=new Context();
        context.setVariable("userName",contract.getName());
        context.setVariable("contractNo",contract.getContractNo());
        context.setVariable("contractOrder",contract.getContractOrder());
        //通过模板引擎处理
        String mailText=templateEngine.process(TEMPLATE_CONTRACT_CREATED,context);
        MimeMessage mimeMailMessage=javaMailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMailMessage);
        helper.setSubject("感谢您成功订购：【"+contract.getCourseName()+"】");
        helper.setFrom(username);
        helper.setTo(contract.getEmail());
        helper.setText(mailText,true);
        javaMailSender.send(mimeMailMessage);

    }


}
